<template>
    <div class="apiList">
        <div class="toolBar">
            <el-input placeholder="输入关键字名回车" v-model="keyword"
                @keydown.enter="pageNum = 1; pageSize = 10; getPermitsList()"
                @clear="pageNum = 1; pageSize = 10; getPermitsList()" style="width:300px;" clearable prefix-icon="Search">
            </el-input>
            <el-button style="margin-left:10px;" type="primary" @click="isAdd=true;permits={};showPermitsInfo=true;roleSelecteds=[];getRoleList()" icon="Plus">添加API权限</el-button>
            <el-button @click="removePermits" style="margin-left:10px" type="danger" icon="Delete">删除API权限</el-button>
        </div>
        <el-table header-row-class-name="tableHeader" border stripe highlight-current-row :data="tableData" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="apiDescribe" label="API权限描述">
                <template #default="scope">
                    <div class="inlineName">
                        <div v-if="scope.row.enabled" class="point" style="background-color:#67C23A"></div>
                        <div v-if="!scope.row.enabled" class="point" style="background-color:#F56C6B"></div>
                        <div>{{scope.row.apiDescribe}}</div></div>
                </template>
            </el-table-column>
            <el-table-column prop="apiPath" label="API路径规则"/>
            <el-table-column prop="apiAllowRoles" label="允许权限角色">
                <template #default="scope">
                    <el-tag type="info" style="margin-right:10px;" v-for="item in scope.row.roleList" :key="item.id">{{item.roleName}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="createTime" label="创建时间" width="200"/>
            <el-table-column align="center" prop="createTime" label="设置"  width="120">
                <template #default="scope">
                    <el-button @click="setting(scope.row)" icon="Setting" round type="info" size="small">设置</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination @current-change="goPage" hide-on-single-page small background layout="prev, pager, next" :total="total" />
        </div>
        <el-dialog title="API权限信息" v-model="showPermitsInfo">
            <el-form :model="permits" label-width="120px">
                <el-form-item label="权限描述">
                    <el-input placeholder="权限描述" v-model="permits.apiDescribe"></el-input>
                </el-form-item>
                <el-form-item label="权限路径规则">
                    <el-input placeholder="权限路径规则" v-model="permits.apiPath"></el-input>
                </el-form-item>
                <el-form-item label="权限允许角色">
                    <el-select @change="handleSelectRole" style="width:100%;" multiple v-model="roleSelecteds"
                        placeholder="选择角色">
                        <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-switch v-model="permits.enabled"></el-switch>
                </el-form-item>
                <el-form-item>
                    <el-button type="info" @click="showPermitsInfo=false">取消</el-button>
                    <el-button @click="saveOrUpdate" type="primary">{{isAdd?'添加':'修改'}}</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import {permitsList,delPermits,addPermits,setPermits,roleList} from '../../js/api.js'
export default {
    data() {
        return {
            keyword: '',
            tableData: [],
            showPermitsInfo: false,
            isAdd: true,
            permits:{},
            selectedIds:[],
            roleList:[],
            roleSelecteds:[],
            pageNum: 1,
            pageSize: 10,
            total: 0,
        }
    },
    methods:{
        getPermitsList(){
            permitsList({pageNum:this.pageNum,pageSize:this.pageSize,keyword:this.keyword}).then(res=>{
                if(!res.status){
                    ElMessage({type:'error',message:res.msg});
                    return;
                }
                this.tableData = res.data.list;
                this.total = res.data.total;
                this.pageNum = 1;
            })
        },
        goPage(currentPageNum){
            this.pageNum = currentPageNum;
            this.getPermitsList();
        },
        setting(permits){
            this.roleSelecteds = [];
            this.permits = permits;
            this.isAdd = false;
            this.getRoleList();
            this.permits.roleList.forEach(role => {
                this.roleSelecteds.push(role.id)
            });
            this.showPermitsInfo = true;
        },
        handleSelectionChange(val){
            this.selectedIds = [];
            val.forEach(element => {
                this.selectedIds.push(element.id);
            });
        },
        removePermits(){
            if(this.selectedIds.length==0){
                ElMessage({type:'warning',message:'请先选择要删除的权限'})
                return;
            }
            ElMessageBox.confirm('该操作将删除选中的权限信息，删除后路径规则将不进行权限校验，是否继续？','提示',{confirmButtonText:'确定',cancelButtonText:'取消'}).then(()=>{
                delPermits(this.selectedIds).then(res=>{
                    ElMessage({type:res.status?'success':'error',message:res.msg})
                    if(res.status) this.getRoleList();
                })
            })
        },
        saveOrUpdate(){
            if(this.isAdd){
                addPermits(this.permits).then(res=>{
                    ElMessage({type:res.status?'success':'error',message:res.msg})
                    if(res.status) this.getPermitsList();
                })
            }else{
                setPermits(this.permits).then(res=>{
                    ElMessage({type:res.status?'success':'error',message:res.msg})
                    if(res.status) this.getPermitsList();
                })
            }
            this.showPermitsInfo = false;
        },
        getRoleList() {
            roleList().then(res => { this.roleList = res.data.list })
        },
        /**
         * 处理选择角色后将角色代码拼接为数据库存储的字符串
         */
        handleSelectRole() {
            let roleCodes = [];
            this.roleSelecteds.forEach(roleId => {
                let obj = this.roleList.find(value => {
                    return value.id == roleId;
                })
                if (obj) {
                    roleCodes.push(obj.roleCode);
                }
            });
            let roles = "";
            for (let i = 0; i < roleCodes.length; i++) {
                if (i == roleCodes.length - 1) {
                    roles = roles + roleCodes[i];
                } else {
                    roles = roleCodes[i] + "," + roles;
                }
            }
            this.permits.apiAllowRoles = roles;
        }
    },
    mounted(){
        this.getPermitsList();
    }
}
</script>
<style scoped>
.point{
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 10px;
}
.inlineName{
    display: flex;
    align-items: center;
}
/* .el-table>>> .tableHeader th{
    background-color: #909399;
    color: white;
    border-color: gray;
} */
</style>